package com.baike.service.impl;

import com.baike.entity.User;
import com.baike.mapper.UserMapper;
import com.baike.mapper.UserRoleMapper;
import com.baike.service.IUserService;
import com.baike.util.MD5Utils;
import com.baike.util.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author x_FG
 * @since 2021-10-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public boolean insertUserInfo(User user, Integer[] roleIds) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        // 增加用户表 返回主键
        user.setPwd("111");
        String s = ShiroUtils.generateSalt(6);
        String md5 = ShiroUtils.encryptPassword("MD5", user.getPwd(), s, 3);
        user.setSalt(s);
        user.setPwd(md5);
        userMapper.insertUser(user);
        // 获取主键 增加 user_role
        Integer uid = user.getUid();
        int i = userRoleMapper.insertUserRole(uid,roleIds);
        return true;
    }

    @Override
    public User getUserById(Integer uid) {
        return userMapper.selectById(uid);
    }

    @Override
    public boolean updateUserInfo(User user, Integer[] roleIds) {
        try {
            // 修改 用户表
            userMapper.updateById(user);
            // 删除 中间表 user_role
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uid",user.getUid());
            userRoleMapper.delete(wrapper);
            // 增加中间表 user_role
            userRoleMapper.insertUserRole(user.getUid(),roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteUserById(Integer uid) {
        try {
            // 删除用户表
            userMapper.deleteById(uid);
            // 删除 中间表 user_role
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uid",uid);
            userRoleMapper.delete(wrapper);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    // 登录调用方法
    @Override
    public User qurieName(String username) {
        User user = userMapper.selectByName(username);
        return user;
    }
}
